package cn.ivicar.app.resource;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.servlet.RequestScoped;

import cn.com.carsmart.exception.BadRequestException;
import cn.com.carsmart.exception.CarsmartException;
import cn.com.carsmart.exception.InternalErrorException;
import cn.com.carsmart.exception.NotAuthorizedException;
import cn.com.carsmart.exception.util.ExceptionResponseBuilder;
import cn.com.carsmart.sae.annotation.RequiresAuthentication;
import cn.com.carsmart.ws.model.SimFlowPackageInfo;
import cn.com.carsmart.ws.util.CacheUtil;
import cn.ivicar.app.controller.OrderController;
import cn.ivicar.app.controller.RelationController;
import cn.ivicar.app.controller.sae.CurrentUtil;
import cn.ivicar.sim.controller.SimController;
import net.sf.json.JSONObject;

@Path("sim/flow")
@RequestScoped
public class SimFlowResource {

	private static transient final Logger LOGGER = LoggerFactory.getLogger(SimFlowResource.class);

	@Inject
	private SimController simController;
	@Inject
	private RelationController relationController;
	@Inject
	private OrderController orderController;
	@Context
	protected HttpServletRequest request;

	// {"iccid":xxx,"userCode":xxx,"unuse":xxx,"operator":xxx,"cardStatus:xxx}
	// 卡号、用户码、未使用流量、运营商、卡状态

	@RequiresAuthentication
	@Path("{iccid}")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response getSurplusFlow(@PathParam("iccid") String iccid) {
		try {
			Long customerId = CurrentUtil.getCustomerId();
			relationController.validate(customerId, iccid);
			JSONObject result = simController.getSimFlowInfo(iccid);
			return CacheUtil.noCache(Response.ok(result)).build();
		} catch (Exception e) {
			LOGGER.error("请求SIM卡剩余流量出错:", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	@RequiresAuthentication
	@GET
	@Path("packages/{iccid}")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response getFlowPackages(@PathParam("iccid") String iccid) {
		try {

			Long customerId = CurrentUtil.getCustomerId();
			relationController.validate(customerId, iccid);
			JSONObject result = simController.getAvailableFlowPackageArray(iccid);
			return CacheUtil.noCache(Response.ok(result)).build();
		} catch (Exception e) {
			LOGGER.error("请求可用流量包套餐异常:", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	@RequiresAuthentication
	@POST
	@Path("packages/{packageId}/recharge/{iccid}/{appId}")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response recharge(@PathParam("packageId") String packageId, @PathParam("iccid") String iccid,
			@PathParam("appId") String appId) {
		try {
			Long customerId = CurrentUtil.getCustomerId();
			relationController.validate(customerId, iccid);

			String ip = request.getHeader("x-forwarded-for");
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}

			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}

			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}

			JSONObject result = simController.buyFlowPackage(customerId,iccid, packageId, appId, ip);
			return CacheUtil.noCache(Response.ok(result)).build();
		} catch (Exception e) {
			LOGGER.error("流量充值出错:", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	@RequiresAuthentication
	@GET
	@Path("orders")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response orderList(@QueryParam("pageIndex") Integer pageIndex, @QueryParam("pageSize") Integer pageSize) {
		try {

			Long customerId = CurrentUtil.getCustomerId();
			JSONObject result = orderController.getOrderList(customerId, pageIndex, pageSize);

			return CacheUtil.noCache(Response.ok(result)).build();
		} catch (Exception e) {
			LOGGER.error("请求流量充值订单列表异常:", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	@RequiresAuthentication
	@GET
	@Path("orders/detail")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response orderDetail(@QueryParam("id") String idStr) {
		try {

			Long customerId = CurrentUtil.getCustomerId();
			JSONObject result = orderController.getOrderDetail(customerId, idStr);
			return CacheUtil.noCache(Response.ok(result)).build();
		} catch (Exception e) {
			LOGGER.error("请求流量充值订单详情异常:", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	@RequiresAuthentication
	@DELETE
	@Path("orders")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response deleteOrder(@QueryParam("id") String idStr) {
		try {

			Long customerId = CurrentUtil.getCustomerId();
			orderController.deleteOrder(customerId, idStr);
			return CacheUtil.noCache(Response.ok()).build();
		} catch (Exception e) {
			LOGGER.error("删除订单异常:", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}
	
	@RequiresAuthentication
	@GET
	@Path("initpackages/{iccid}")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response initFlowPackages(@PathParam("iccid") String iccid) {
		try {

			Long customerId = CurrentUtil.getCustomerId();
			relationController.validate(customerId, iccid);
			List<SimFlowPackageInfo> result = simController.getAvailableFlowPackageList(iccid);
			LOGGER.info("刷新流量平台可用套餐数据结束");
			return CacheUtil.noCache(Response.ok(result)).build();
		} catch (Exception e) {
			LOGGER.error("刷新可用流量包套餐异常:", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}
}
